﻿using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Shop.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Shop.DB;
using System.Text;
using System.Threading.Tasks;

namespace Shop.Application.Cart
{
    public class AddToCart
    {
        private ISession _session;
        private DBContext _context;

        public AddToCart(ISession session,DBContext context)
        {
            _session = session;
            _context = context;
        }

        public async Task<bool> Do(CartInput model)
        {
            var stock = _context.Stocks.Where(x => x.StockID == model.StockID).FirstOrDefault();
            var stockHolds = _context.StockHolds.Where(x => x.SessionID == _session.Id).ToList();
            if (stock.Count < model.Count)
                return false;

            _context.StockHolds.Add(new StockHold
            {
                StockID = stock.StockID,
                Count = model.Count,
                SessionID=_session.Id,
                ExpiryDate = DateTime.Now.AddMinutes(30)
            });
            stock.Count -= model.Count;
            foreach (var item in stockHolds)
            {
                item.ExpiryDate = DateTime.Now.AddMinutes(30);
            }
            await _context.SaveChangesAsync();

            var cartList = new List<CartProduct>();
            var str =_session.GetString("Cart");
            if (!string.IsNullOrEmpty(str))
            {
                cartList = JsonConvert.DeserializeObject<List<CartProduct>>(str);
            }
            if (cartList.Any(x => x.StockID == model.StockID))
            {
                cartList.Find(x => x.StockID == model.StockID).Count += model.Count;
            }
            else
            {
                cartList.Add(new CartProduct()
                {
                    StockID = model.StockID,
                    Count = model.Count
                });
            }
            str = JsonConvert.SerializeObject(cartList);
            _session.SetString("Cart", str);
            return true;
        }
    }
}
